const env = require('./config.js'); //配置文件，在这文件里配置你的OSS keyId和KeySecret,timeout:87600;
import moment from './moment.js'

const base64 = require('./base64.js');//Base64,hmac,sha1,crypto相关算法
require('./hmac.js');
require('./sha1.js');
const Crypto = require('./crypto.js');


import {api} from '@/pagesCircle/api.js'  //上传接口

/*
 *上传文件到阿里云oss
 *@param - filePath :图片的本地资源路径
 *@param - dir:表示要传到哪个目录下
 *@param - successc:成功回调
 *@param - failc:失败回调
 */ 
const uploadFile = function (filePath,fileParm,dir="", successc, failc) {


  if (!filePath || filePath.length < 9) {
    uni.showModal({
      title: '文件错误',
      content: '请重试',
      showCancel: false,
    })
    return;
  }
  //获取文件后缀
  let suffx = filePath.substring(filePath.lastIndexOf(".") +1);
  
  //图片正则
  let imgSXE = /(\.bmp|\.gif|\.jpg|\.jpeg|\.png|\.svg|\.webp)$/i;
  //视频格式
  let videoSXE = /(\.ogg|\.mp4|\.webm|\.avi|\.flv|\.wmv|\.mkv|\.m2v|\.3GP|\.mov|\.vi)$/i;
  
  let mimetype = "" //文件类型  
  let file_class = 0  //文件类型1-图片2-视频3-文件  
  if(imgSXE.test(filePath)){
	  file_class = 1
	  mimetype  = "image"
  }else if(videoSXE.test(filePath)){
	  mimetype  = "video"
	  file_class = 2
  }else{
	  file_class = 3
	  mimetype ="files"
  }
  
  //存储文件目录不存在
  if(!dir && mimetype){
	  dir = mimetype + "/"
  }


  let ymd = moment().format("YYYYMMDD") + "/";
  //名字 可以自行定义，     这里是采用当前的时间戳 + 150内的随机数来给图片命名的
  const fileUrl = dir + ymd  + new Date().getTime() + parseInt(Math.random() * ( 9999 - 1000 + 1 ) + 1000, 10)
  const aliyunFileKey = fileUrl + "." +suffx;
  
  const aliyunServerURL = env.uploadImageUrl;//OSS地址，需要https
  const accessid = env.OSSAccessKeyId;
  const policyBase64 = getPolicyBase64();
  const signature = getSignature(policyBase64);//获取签名
 
  uni.uploadFile({
    url: aliyunServerURL,//开发者服务器 url
    filePath: filePath,//要上传文件资源的路径
    name: 'file',//必须填file
    formData: {
      'key': aliyunFileKey,
      'policy': policyBase64,
      'OSSAccessKeyId': accessid,
      'signature': signature,
      'success_action_status': '200',
    },
    success: function (res) {
			//console.log(res,aliyunServerURL+aliyunFileKey);
      if (res.statusCode != 200) {
        failc(new Error('上传错误:' + JSON.stringify(res)))
        return;
      }
	  //文件信息上传到服务器
	  let parData = {
		  url:aliyunFileKey,
		  file_class:file_class,
		  mimetype:mimetype+"/"+suffx,
		  filesize:fileParm.size || 0
	  }
	  api.postCircleDynamicSavefiles(parData).then(resItem=>{
		  let succ = {
			  files_id:resItem.files_id,
			  url:aliyunServerURL+aliyunFileKey
		  }
		  successc(succ);
	  }).catch(errItem=>{
		   let succ = {
			  files_id:0,
			  url:aliyunServerURL+aliyunFileKey
		   }
		   successc(succ);
	  })
	  
       
    },
    fail: function (err) {
      err.wxaddinfo = aliyunServerURL;
      failc(err);
    },
  })
}

const getPolicyBase64 = function () {
  let date = new Date();
  date.setHours(date.getHours() + env.timeout);
  let srcT = date.toISOString();
  const policyText = {
    "expiration": srcT, //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了 
    "conditions": [
      ["content-length-range", 0, 100 * 1024 * 1024] // 设置上传文件的大小限制,100mb
    ]
  };

  const policyBase64 = base64.encode(JSON.stringify(policyText));
	console.log(policyBase64);
  return policyBase64;
}

const getSignature = function (policyBase64) {
  const accesskey = env.AccessKeySecret;

  const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
    asBytes: true
  });
  const signature = Crypto.util.bytesToBase64(bytes);
console.log(signature);
  return signature;
}

module.exports = uploadFile;